// pages/community/community.js
import { requestData } from '../../utils/ajax'
import { toPage, formatTime } from '../../utils/util'
const api = require('../../utils/api')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    cardsNum: 0,
    hotCards: [], // 经验热帖
    cards: [], // 众说纷坛
    tab: 0,
    hotClass: ['hot active', 'hot'],
    talkClass: ['talk active', 'talk'],
    first: true,
    theYear: '', // 考研年份
    remainTime: '',
  },
  // 获取考研天数相关信息
  getDays(y, m, d) {
    y = y * 1
    m = m * 1
    d = d * 1
    const isLeap = (y % 400 === 0) || (y % 4 === 0 && y % 100 !== 0) ? 1 : 0
    const days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    days[2] += isLeap
    let day = d
    for (let i = 1; i < m; i++) {
      day += days[i]
    }
    return day
  },
  // 获取考研天数相关信息
  getCountdown() {
    const DEADLINE = getApp().globalData.DEADLINE
    const date = new Date()
    const time = formatTime(date).split(' ')[0]
    const theYear = time.split('-')[0] * 1 + 1 // 考研年份
    const theMonth = time.split('-')[1]
    const theDay = time.split('-')[2]
    const remainTime = this.getDays(theYear, DEADLINE[0], DEADLINE[1]) - this.getDays(theYear, theMonth, theDay)
    console.log(theYear, remainTime)
    this.setData({theYear, remainTime})
  },
  toPage(event) {
    let data = this.data.cards
    toPage(event, data)
  },
  showtab(event) {
    const { tab } = event.currentTarget.dataset
    this.setData({tab})
  },
  reGetCards() {
    api.getAllCards().then(cards => {
      // console.log(cards);
      cards.reverse()
      this.setData({cardsNum: cards.length})
      const hotCards = cards.filter(item => {
        return item.type == 2
      })
      this.setData({cards, hotCards})
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCountdown()
    // 仅页面第一次加载时，才调用一次，其他的全在 onShow 中调用
    // 防止页面白屏
    if (this.data.first) {
      this.reGetCards()
      this.setData({first: false})
    }
    
    // requestData('community', (data) => {
    //   const cards = data.cards
    //   const hotCards = [cards[1]]
    //   this.setData({cards, hotCards})
    //   this.setData({cardsNum: cards.length})
    //   // this.setData({cards: data.cards})
    // })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 页面不是第一次加载时，才调用——用于数据更新
    if (!this.data.first) {
      this.reGetCards()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})